/**
 * 博客路由
 */
const router = require('koa-router')()
const { getList, getDetail, createBlog, editBlog, deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { getCurrentTime } = require('../util/currentTime')
const { loginCheck } = require('../util/checkLogin')

router.prefix('/api/blog')

router.post('/create', async function (ctx, next) {
    const postData = ctx.request.body
    const title = postData.title
    const content = postData.content
    const author = postData.author
    const promiseValue = await createBlog(title, content, author, getCurrentTime(), getCurrentTime())
    if (promiseValue.insertId) {
        ctx.body = new SuccessModel({
            tip: '创建成功',
            createTime: getCurrentTime()
        }, '创建博客')
    } else {
        ctx.body = new ErrorModel({
            tip: '创建失败',
            failTime: getCurrentTime()
        }, '创建博客')
    }
})

router.post('/edit', async function (ctx, next) {
    const postData = ctx.request.body
    const title = postData.title
    const content = postData.content
    const author = postData.author
    const id = ctx.query.id
    const promiseValue = await editBlog(title, content, author, getCurrentTime(), id)
    if (promiseValue.affectedRows) {
        ctx.body = new SuccessModel({
            tip: '编辑成功',
            updateTime: getCurrentTime()
        }, '编辑博客')
    } else {
        ctx.body = new ErrorModel({
            tip: '编辑失败',
            failTime: getCurrentTime()
        }, '编辑博客')
    }
})

router.get('/list', loginCheck, async function (ctx, next) {
    const author = ctx.query.author
    const keyword = ctx.query.keyword
    const promiseValue = await getList(author, keyword)
    ctx.body = new SuccessModel(promiseValue, '博客列表')
})

router.get('/detail', async function (ctx, next) {
    const id = ctx.query.id
    const promiseValue = await getDetail(id)
    console.log('promiseValue', promiseValue)
    if (promiseValue.length > 0) {
        ctx.body = new SuccessModel(promiseValue[0], '博客详情')
    } else {
        ctx.body = new ErrorModel({
            tip: '查询失败，无此博客',
            failTime: getCurrentTime()
        }, '博客详情')
    }
})

router.post('/delete', async function (ctx, next) {
    const id = ctx.query.id
    const promiseValue = await deleteBlog(id)
    if (promiseValue.affectedRows) {
        ctx.body = new SuccessModel({
            tip: '删除成功',
            deleteTime: getCurrentTime()
        }, '删除博客')
    } else {
        ctx.body = new ErrorModel({
            tip: '删除失败',
            failTime: getCurrentTime()
        }, '删除博客')
    }
})


module.exports = router
 